<?php

class BindXml {
    public function bind($file) {
        $xml = file_get_contents($file);

        $obj = new SimpleXMLElement($xml);
        $components = new Components();

        $enviroment = new Enviroment();
        $enviroment->setBaseDir($obj->enviroment->{'base-dir'});

        $components->setEnviroment($enviroment);

        
        $compArray = array();

        foreach ($obj->component as $comp) {
            $component = new Component();
            $component->setId((string)$comp['id']);
            $component->setClass((string)$comp['class']);
            $component->setScope((string)$comp['scope']);
            $component->setBaseDir((string)$comp['base-dir']);

            $propArray = array();

            foreach ($comp->property as $prop) {
                $property = new Property();
                $property->setName((string)$prop['name']);
                if ($prop->ref) {
                    $property->setRef((string)$prop->ref['id']);
                } elseif ($prop->value) {
                    $property->setValue((string)$prop->value);
                }
                $propArray[(string)$prop['name']] = $property;
            }

            $component->setProperties($propArray);

            $constructor = array();

            foreach ($comp->{'constructor-arg'} as $arg) {
                $argument = new Argument();
                if ($arg->ref) {
                    $argument->setRef((string)$arg->ref['id']);
                } elseif ($arg->value) {
                    $argument->setValue((string)$arg->value);
                }
                $constructor[] = $argument;
            }

            $component->setConstructor($constructor);

            $compArray[(string)$comp['id']] = $component;
        }

        $components->setComponents($compArray);

        return $components;
    }
}